package com.iss.yunpan.service.impl;

import com.iss.yunpan.dao.FileDao;
import com.iss.yunpan.entity.FileContent;
import com.iss.yunpan.entity.Users;
import com.iss.yunpan.service.FileService;
import com.obs.services.ObsClient;
import com.obs.services.model.CopyObjectResult;
import com.obs.services.model.ObsObject;
import com.obs.services.model.TemporarySignatureRequest;
import com.obs.services.model.TemporarySignatureResponse;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.nio.cs.US_ASCII;

import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Date;
import java.util.List;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private HttpSession session;
    private String endPoint="obs.cn-east-3.myhuaweicloud.com";
    private String ak="N70O0XEWDEHGO4YA38CY";
    private String sk="oTZKNwTav6FBkRR0HBmUFamjHHrxF9qvYCU3SYOj";
    private String bucaketname="senventh";

    @Autowired

    private FileDao dao;
    private Object InputStream;
    private String bucketname;

    @Override
    public List<FileContent> getAllFile(String fileName,String parentId){

        return dao.getAllFile(fileName,parentId);
    }
    @Override
    public List<FileContent> getAllShare(String id, String parentId) {

        return dao.getAllShare(id,parentId);
    }







    @Override
    public void uploadFile(String fileName, InputStream input, String parentId) throws IOException {
        Users user = (Users) session.getAttribute("users");
        if (user != null && !user.getUserId().equals("")) {
        FileContent con=dao.getFileContentByFileNameAndParentId(fileName,Integer.valueOf(parentId));
            if (con != null) {
                con.setFileSize(input.available() + "kb");
                con.setUploadTime(new Date());
                dao.updateFile(con);
            } else {

                    FileContent cont = new FileContent();
                    cont.setFileName(fileName);
                    cont.setFileSize(input.available() + "kb");
                    cont.setFileAbsolute(fileName);
                    cont.setFileType(fileName.substring(fileName.lastIndexOf("."), fileName.length()));
                    cont.setParentId(Integer.valueOf(parentId));
                    cont.setUserId(user.getUserId());
                    cont.setUploadTime(new Date());
                    dao.insertFile(cont);

                    ObsClient obsClient = new ObsClient(ak, sk, endPoint);
                    obsClient.putObject(bucaketname, fileName, input);

                }
            }

    }

    @Override
    public boolean checkFileContent(String fileName, Integer parentId) {
        FileContent cont=dao.getFileContentByFileNameAndParentId(fileName,parentId);
        if(cont!=null){
            return true;
        }
        return false;
    }

    @Override
    public void insertFloder(String fileName, Integer parentId) {
        Users user = (Users) session.getAttribute("users");
        if (user != null && !user.getUserId().equals("")) {
            FileContent con = new FileContent();
            con.setFileName(fileName);
            con.setParentId(parentId);
            con.setUploadTime(new Date());
            con.setUserId(user.getUserId());
            con.setFileType("文件夹");
            con.setFileAbsolute(fileName);
            dao.insertFile(con);

            ObsClient obsClient = new ObsClient(ak, sk, endPoint);
            obsClient.putObject(bucaketname, fileName, new ByteArrayInputStream(new byte[0]));
        }
    }
    @Override
    public byte[] download(String fileAbsolute) throws IOException {
        try{
            ObsClient obsClient = new ObsClient(ak, sk, endPoint);
            ObsObject obsObject = obsClient.getObject(bucaketname, fileAbsolute);// 读取对象内容
            InputStream input = obsObject.getObjectContent();
            byte[] b = new byte[1024];
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len;
            while ((len=input.read(b)) != -1){
                bos.write(b, 0, len);
            }
            byte[] out =  bos.toByteArray();
            bos.close();
            input.close();
            return out;
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String getFile(String fileAbsolute){
        System.out.println("执行预览操作");
        String resultUrl;
        String ObjectKey=fileAbsolute;
        TemporarySignatureRequest request=new TemporarySignatureRequest();
        request.setBucketName(bucaketname);
        request.setObjectKey(ObjectKey);
        request.setRequestDate(new Date());
        request.setExpires(60*60*60*24);
        ObsClient obsClient = new ObsClient(ak, sk, endPoint);
        TemporarySignatureResponse signature = obsClient.createTemporarySignature(request);
        resultUrl=signature.getSignedUrl();
        System.out.println("临时链接"+resultUrl);
        return resultUrl;
    }

    @Override
    public void share(String fileAbsolute) {
        dao.share(fileAbsolute);
    }

    @Override
    public void deleteShare(String fileAbsolute) {
        dao.deleteShare(fileAbsolute);
    }

    @Override
    public void collect(String fileAbsolute) {
        dao.collect(fileAbsolute);

    }

    @Override
    public List<FileContent> getAllCollect(String id, String parentId) {
        return dao.getAllCollect(id,parentId);
    }

    @Override
    public void deleteCollect(String fileAbsolute) {
        dao.deleteCollect(fileAbsolute);
    }


    @Override
    public void trash(String fileAbsolute) { dao.trash(fileAbsolute);}


    @Override
    public List<FileContent> getAllTrash(String id, String parentId) {
        return dao.getAllTrash(id,parentId);
    }

    @Override
    public void deleteTrash(String fileAbsolute) {dao.deleteTrash(fileAbsolute);


    }

    @Override
    public void deleteComplete(String fileName) {
        FileContent con=new FileContent();
        con.setFileName(fileName);
        dao.deleteComplete(con);
    }

    @Override
    public void rename(String oldName, String newName) {
        dao.rename(oldName,newName);
    }

    @Override
    public void copyFile(String orignPath,String newPath){
        FileContent orign= dao.getFileContentByPath(orignPath);
        if(!orign.getFileType().equals("文件夹")){
            copy(orignPath,newPath);
        }
    }


    @Override
    public void copy(String orignPath, String newPath) {
        FileContent con = dao.getFileContentByPath(orignPath);
        String tail=newPath.endsWith("/") ? "" : "/";
        if (!newPath.equals("")) {
            con.setFileAbsolute(newPath + tail + con.getFileName());
        }else{
            con.setFileAbsolute(con.getFileName());
        }
        if(con.getFileAbsolute().equals(orignPath)){
            con.setFileAbsolute(con.getFileName().replace(".","副本."));
            con.setFileName(con.getFileName().replace(".","副本."));
        }
        con.setParentId(0);//cont==null?0:cont.getId()
        con.setUploadTime(new Date());
        con.setDeleteFlag(0);
        con.setCollectFlag(0);
        con.setShareFlag(0);
        dao.insertFile(con);
    }


}
